package org.six11.olive3.util;

import java.util.*;

import org.six11.util2.Debug;

/**
 * A collection of static functions that don't belong anywhere in particular.
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 * 
 */
public abstract class MiscFunctions {
  public static int safeInt(String in) {
    int ret = 0;
    try {
      ret = Integer.parseInt(in);
    } catch (NumberFormatException ignore) {
    }
    return ret;
  }

  public static long safeLong(String in) {
    long ret = (long) 0;
    try {
      ret = Long.parseLong(in);
    } catch (NumberFormatException ignore) {
    }
    return ret;
  }

  public static void outputMap(Map m) {
    for (Object k : m.keySet()) {
      Debug.out("MiscFuntions", "map: " + k + " => " + m.get(k));
    }
  }

  public static <T> Collection<T> emptyCollection() {
    return new ArrayList<T>();
  }

  public static <K, V> Map<K, V> emptyMap() {
    return new HashMap<K, V>();
  }

  /**
   * Accepts an input string that may (or may not) include unescaped double quotes, and returns a
   * string that includes a backslash before the quotes. It does make sure that a sequence that is
   * already escaped gets doubly-escaped. So, " becomes \", but \" remains \".
   */
  public static String escape(String in) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < in.length(); i++) {
      if (in.charAt(i) == '"' && i > 0 && in.charAt(i - 1) != '\\') {
        buf.append("\\" + in.charAt(i));
      } else if (in.charAt(i) == '"' && i == 0) {
        buf.append("\\" + in.charAt(i));
      } else {
        buf.append(in.charAt(i));
      }
    }
    return buf.toString();
  }

  /**
   * Like 'escape' in reverse. It replaces sequences of \" with ".
   */
  public static String unescape(String in) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < in.length(); i++) {
      if (in.charAt(i) == '\\' && (i+1 < in.length()) && in.charAt(i+1) == '"') {
        buf.append("\"");
        i = i+1;
      } else {
        buf.append(in.charAt(i));
      }
    }
    return buf.toString();
  }

  public static void main(String[] args) {
    test("This has \"quotes\" ok?");
    test("\"This string is quoted entirely.\"");
    test("\"This string has \"internal\" quotes.\"");
    test("This string has \\\"already\\\" escaped quotes.");
    test("Now a \\\\ string that has \\ slashes without quotes.\\");
  }

  public static void test(String in) {
    System.out.println("Input    : " + in);
    String out = escape(in);
    System.out.println("Escaped  : " + out);
    String unescaped = unescape(out);
    System.out.println("Unescaped: " + unescaped);
  }
}
